import { getInstanceByDom, init } from "echarts";
import { useEffect, useRef } from "react";

type RadarChartOptions = {
    indicator: Array<string>,
    seriesData: Array<Array<number>>,
};

const RadarChart = ({ options }: { options: RadarChartOptions }) => {
    const { indicator, seriesData } = options;

    // 放置图表的元素
    const chartRef = useRef(null);

    // 初始化图表
    useEffect(() => {
        const myChart = init(chartRef.current);
        // 开始观察
        const observer = new ResizeObserver(() => myChart?.resize());
        observer.observe(chartRef.current!);
        // 结束观察，清理图表
        return () => {
            observer.disconnect();
            myChart.dispose();
        };
    }, []);

    // 更新图表
    useEffect(() => {
        // 1. 生成实例
        const myChart = getInstanceByDom(chartRef.current!);
        // 2. 准备图表参数
        const option = {
            color: ['#67F9D8', '#FFE434', '#56A3F1', '#FF917C'],
            title: { text: '雷达图', textAlign: 'center', top: 8, left: '50%' },
            legend: { top: 56, left: 'center' },
            radar: [
                {
                    indicator: indicator.map(item => ({ name: item })),
                    center: ['50%', '60%'],
                    radius: 120,
                    startAngle: 90,
                    splitNumber: 4,
                    shape: 'circle',
                    axisName: {
                        formatter: '{value}',
                        color: '#428BD4'
                    },
                    splitArea: {
                        areaStyle: {
                            color: ['#77EADF', '#26C3BE', '#64AFE9', '#428BD4'],
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowBlur: 10
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(211, 253, 250, 0.8)'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(211, 253, 250, 0.8)'
                        }
                    }
                },
            ],
            series: [
                {
                    type: 'radar',
                    emphasis: {
                        lineStyle: {
                            width: 4
                        }
                    },
                    data: seriesData.map((item, index) => ({ value: item, name: `data${index}` })),
                },
            ],
        };
        // 3. 渲染参数
        myChart?.setOption(option);
    }, [indicator, seriesData]);

    return (
        <div ref={chartRef} style={{ width: '100%', height: '100%' }} />
    );
};

export default RadarChart;